import time
from django.utils.deprecation import MiddlewareMixin

class RequestTimingMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request._start_time = time.time()

    def process_response(self, request, response):
        if hasattr(request, '_start_time'):
            duration = (time.time() - request._start_time) * 1000  # 转换为毫秒
            # 添加请求耗时到响应头
            response['X-Request-Duration-ms'] = f"{duration:.2f}"
        return response